package com.xmut.xmutbackend.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmut.xmutbackend.entity.OperationLog;
import com.xmut.xmutbackend.entity.PageBean;
import com.xmut.xmutbackend.mapper.OperationLogMapper;
import com.xmut.xmutbackend.service.IOperationLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 邓仲良
 * @since 2025-06-18
 */
@Service
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements IOperationLogService {

    @Autowired
    private OperationLogMapper operationLogMapper;

    @Override
    public PageBean<OperationLog> getOperationLogList(String name, Integer page, Integer pageSize) {
        Page<OperationLog> p = new Page<>(page, pageSize);
        List<OperationLog> list = operationLogMapper.operationLogPage(p,name);
        PageBean<OperationLog> pageBean = new PageBean<OperationLog>(p.getTotal(),list);
        return pageBean;
    }

    @Override
    public void recordLog(Long id, String username, String method, String url, String ip, Integer status) {
        try {
            OperationLog log = new OperationLog();
            
            // 用户ID处理，只设置userId，不设置id (让数据库自动生成日志ID)
            if (id != null) {
                log.setUserId(Math.toIntExact(id));
            } else {
                // 当id为null时，使用null表示未知用户
                log.setUserId(null);
            }
            
            // 用户名处理，确保有有效值
            log.setUsername(username != null ? username : "未知用户");
            
            // 设置操作相关信息
            log.setOperation(getOperationName(url)); // 提取操作名称
            log.setMethod(method);
            log.setUrl(url);
            log.setIp(ip);
            
            // 设置状态
            log.setStatus(String.valueOf(status));
            
            // 设置创建时间
            log.setCreateTime(LocalDateTime.now());
            
            // 插入日志记录
            operationLogMapper.insert(log);
        } catch (Exception e) {
            // 打印错误信息，但不要让日志记录失败影响主要业务流程
            System.err.println("记录操作日志失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 根据URL提取操作名称
     */
    private String getOperationName(String url) {
        if (url == null) return "未知操作";
        
        // 提取主要操作
        String operation = url;
        
        // 移除URL参数
        if (operation.contains("?")) {
            operation = operation.substring(0, operation.indexOf("?"));
        }
        
        // 处理常见URL模式
        if (operation.contains("/users/login")) {
            return "用户登录";
        } else if (operation.contains("/index")) {
            return "访问首页";
        } else if (operation.contains("/stats")) {
            return "查看统计";
        } else if (operation.contains("/upload")) {
            return "文件上传";
        }
        
        // 根据HTTP方法标识操作类型
        if (url.toLowerCase().contains("get")) {
            return "查询" + operation;
        } else if (url.toLowerCase().contains("post")) {
            return "新增" + operation;
        } else if (url.toLowerCase().contains("put")) {
            return "更新" + operation;
        } else if (url.toLowerCase().contains("delete")) {
            return "删除" + operation;
        }
        
        return operation;
    }
}

